<template>
  <div class="file-history-panel">
    <el-scrollbar height="100%">
      <div class="history-content">
        <!-- History Timeline -->
        <div class="timeline-container">
          <div class="timeline-header">
            <h4>文件历史时间线</h4>
            <el-text size="small" type="info">
              共 {{ history.length }} 个版本
            </el-text>
          </div>
          
          <div class="timeline">
            <div
              v-for="(record, index) in sortedHistory"
              :key="`${record.versionId}-${record.fileId}`"
              :class="[
                'timeline-item',
                { 
                  'is-current': record.versionId === currentVersion,
                  'is-missing': !record.exists
                }
              ]"
            >
              <!-- Timeline connector -->
              <div class="timeline-connector" v-if="index < sortedHistory.length - 1"></div>
              
              <!-- Timeline dot -->
              <div class="timeline-dot">
                <el-icon v-if="record.exists">
                  <Document />
                </el-icon>
                <el-icon v-else>
                  <Close />
                </el-icon>
              </div>
              
              <!-- Timeline content -->
              <div class="timeline-content">
                <div class="record-header">
                  <div class="record-info">
                    <el-tag 
                      :type="record.versionId === currentVersion ? 'primary' : 'info'"
                      size="small"
                    >
                      {{ formatVersionId(record.versionId) }}
                    </el-tag>
                    <el-text size="small" type="primary">
                      {{ formatDate(record.timestamp) }}
                    </el-text>
                  </div>
                  
                  <div class="record-actions">
                    <el-button-group size="small">
                      <el-tooltip content="切换到此版本">
                        <el-button 
                          :icon="Switch"
                          @click="switchToVersion(record.versionId)"
                          :disabled="record.versionId === currentVersion"
                          text
                        />
                      </el-tooltip>
                      <el-tooltip content="预览此版本">
                        <el-button 
                          :icon="View"
                          @click="previewVersion(record)"
                          :disabled="!record.exists"
                          text
                        />
                      </el-tooltip>
                      <el-tooltip content="与当前版本对比">
                        <el-button 
                          :icon="DocumentCopy"
                          @click="compareWithCurrent(record)"
                          :disabled="!record.exists || record.versionId === currentVersion"
                          text
                        />
                      </el-tooltip>
                    </el-button-group>
                  </div>
                </div>
                
                <div class="record-details">
                  <div class="record-meta">
                    <span class="meta-item">
                      <el-text size="small" type="info">路径:</el-text>
                      <el-text size="small">{{ record.originalPath }}</el-text>
                    </span>
                    <span class="meta-item" v-if="record.size">
                      <el-text size="small" type="info">大小:</el-text>
                      <el-text size="small">{{ formatFileSize(record.size) }}</el-text>
                    </span>
                    <span class="meta-item" v-if="record.source">
                      <el-text size="small" type="info">来源:</el-text>
                      <el-text size="small">{{ record.source }}</el-text>
                    </span>
                  </div>
                  
                  <div v-if="!record.exists" class="missing-notice">
                    <el-alert
                      title="文件在此版本中不存在"
                      type="warning"
                      :closable="false"
                      size="small"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- History Statistics -->
        <div class="history-stats">
          <h4>统计信息</h4>
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-value">{{ existingVersions }}</div>
              <div class="stat-label">存在版本</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ missingVersions }}</div>
              <div class="stat-label">缺失版本</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ timeSpan }}</div>
              <div class="stat-label">时间跨度</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ averageSize }}</div>
              <div class="stat-label">平均大小</div>
            </div>
          </div>
        </div>

        <!-- Quick Actions -->
        <div class="quick-actions">
          <h4>快速操作</h4>
          <div class="action-buttons">
            <el-button 
              type="primary" 
              :icon="Download"
              @click="recoverLatestVersion"
              :disabled="!latestExistingVersion"
            >
              恢复最新版本
            </el-button>
            <el-button 
              type="success" 
              :icon="DocumentCopy"
              @click="compareVersions"
              :disabled="existingVersions < 2"
            >
              版本对比
            </el-button>
            <el-button 
              :icon="Refresh"
              @click="refreshHistory"
            >
              刷新历史
            </el-button>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { 
  Document, 
  Close, 
  Switch, 
  View, 
  DocumentCopy, 
  Download, 
  Refresh 
} from '@element-plus/icons-vue'
import type { FileHistoryRecord } from '../types/basic'

interface Props {
  history: FileHistoryRecord[]
  currentVersion: string | null
}

interface Emits {
  (e: 'selectVersion', versionId: string): void
  (e: 'previewVersion', record: FileHistoryRecord): void
  (e: 'compareVersions', record1: FileHistoryRecord, record2: FileHistoryRecord): void
  (e: 'recoverVersion', record: FileHistoryRecord): void
  (e: 'refreshHistory'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// Computed properties
const sortedHistory = computed(() => 
  [...props.history].sort((a, b) => b.timestamp - a.timestamp)
)

const existingVersions = computed(() => 
  props.history.filter(record => record.exists).length
)

const missingVersions = computed(() => 
  props.history.filter(record => !record.exists).length
)

const latestExistingVersion = computed(() => 
  sortedHistory.value.find(record => record.exists)
)

const timeSpan = computed(() => {
  if (props.history.length < 2) return '-'
  
  const timestamps = props.history.map(record => record.timestamp)
  const earliest = Math.min(...timestamps)
  const latest = Math.max(...timestamps)
  const diffDays = Math.ceil((latest - earliest) / (1000 * 60 * 60 * 24))
  
  return `${diffDays} 天`
})

const averageSize = computed(() => {
  const existingRecords = props.history.filter(record => record.exists && record.size > 0)
  if (existingRecords.length === 0) return '-'
  
  const totalSize = existingRecords.reduce((sum, record) => sum + record.size, 0)
  const avgSize = totalSize / existingRecords.length
  
  return formatFileSize(avgSize)
})

// Methods
function formatVersionId(versionId: string): string {
  return versionId.startsWith('-') ? versionId.substring(1, 9) : versionId.substring(0, 8)
}

function formatDate(timestamp: number): string {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function formatFileSize(size: number): string {
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  let fileSize = size
  
  while (fileSize >= 1024 && unitIndex < units.length - 1) {
    fileSize /= 1024
    unitIndex++
  }
  
  return `${fileSize.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`
}

function switchToVersion(versionId: string) {
  emit('selectVersion', versionId)
}

function previewVersion(record: FileHistoryRecord) {
  emit('previewVersion', record)
}

function compareWithCurrent(record: FileHistoryRecord) {
  const currentRecord = props.history.find(r => r.versionId === props.currentVersion)
  if (currentRecord) {
    emit('compareVersions', record, currentRecord)
  }
}

function recoverLatestVersion() {
  if (latestExistingVersion.value) {
    emit('recoverVersion', latestExistingVersion.value)
  }
}

function compareVersions() {
  const existingRecords = sortedHistory.value.filter(record => record.exists)
  if (existingRecords.length >= 2) {
    emit('compareVersions', existingRecords[0], existingRecords[1])
  }
}

function refreshHistory() {
  emit('refreshHistory')
}
</script>

<style scoped>
.file-history-panel {
  height: 100%;
  padding: 16px;
}

.history-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.timeline-container {
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  padding: 16px;
  background-color: var(--el-bg-color);
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.timeline-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.timeline {
  position: relative;
}

.timeline-item {
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 0;
}

.timeline-item.is-current {
  background-color: var(--el-color-primary-light-9);
  border-radius: 6px;
  padding: 12px;
  margin: 0 -12px;
}

.timeline-item.is-missing {
  opacity: 0.6;
}

.timeline-connector {
  position: absolute;
  left: 11px;
  top: 32px;
  bottom: -12px;
  width: 2px;
  background-color: var(--el-border-color);
}

.timeline-dot {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: var(--el-bg-color);
  border: 2px solid var(--el-color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  z-index: 1;
}

.timeline-item.is-missing .timeline-dot {
  border-color: var(--el-color-warning);
}

.timeline-content {
  flex: 1;
  min-width: 0;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.record-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.timeline-item:hover .record-actions {
  opacity: 1;
}

.record-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.record-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.missing-notice {
  margin-top: 8px;
}

.history-stats {
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  padding: 16px;
  background-color: var(--el-bg-color);
}

.history-stats h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.stat-card {
  text-align: center;
  padding: 12px;
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
  border: 1px solid var(--el-border-color-lighter);
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-color-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.quick-actions {
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  padding: 16px;
  background-color: var(--el-bg-color);
}

.quick-actions h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-buttons .el-button {
  justify-content: flex-start;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .record-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .record-actions {
    opacity: 1;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .timeline-item {
    padding: 8px 0;
  }
  
  .timeline-item.is-current {
    padding: 8px;
    margin: 0 -8px;
  }
}
</style>